package com.googlecode.jaks.swt;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;

import com.googlecode.jaks.common.io.NonClosingInputStream;

/**
 * 
 * @author Jason Smith
 * @requiresDependencyResolution compile
 * @goal find-it
 * @phase package
 */
public class FindItMojo extends InstallArtifactFromHttpMojo
{
	/**
	 * The regular expression pattern of the class we're looking for.
	 * @parameter
	 */
	protected String findItPath = null;
	
	@Override
	protected void processArchive(final File archive) throws FileNotFoundException, IOException
	{
		if(findItPath == null)
		{
			throw new IllegalArgumentException("Find-it-path not specified.");
		}
		
		final TarInputStream tarIn = new TarInputStream(new GZIPInputStream(new BufferedInputStream(new FileInputStream(archive))));
		try
		{
			for(;;)
			{
				final TarEntry entry = tarIn.getNextEntry();
				if(entry == null)
				{
					break;
				}
				
				if(entry.getName().endsWith(".jar"))
				{
					final ZipInputStream zipIn = new ZipInputStream(new NonClosingInputStream(tarIn));
					try
					{
						for(;;)
						{
							final ZipEntry zipEntry = zipIn.getNextEntry();
							if(zipEntry == null)
							{
								break;
							}
							try
							{
								if(zipEntry.getName().matches(findItPath))
								{
									getLog().info(">>> " + entry.getName() + " [" + zipEntry.getName() + "]");
								}
							}
							finally
							{
								zipIn.closeEntry();
							}
						}
					}
					finally
					{
						zipIn.close();
					}
				}
			}
		}
		finally
		{
			tarIn.close();
		}
	}

}
